package com.sc.security.service.impl;

import com.sc.security.common.RequestHolder;
import com.sc.security.dao.SysUserMapper;
import com.sc.security.exception.ParamException;
import com.sc.security.model.SysUser;
import com.sc.security.service.ModifyUserInfoService;
import com.sc.security.utils.BeanValidator;
import com.sc.security.vo.ModifyUserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ModifyUserInfoServiceImpl implements ModifyUserInfoService {

    @Autowired
    private SysUserMapper userMapper;

    @Override
    public void change(ModifyUserVo userVo) {
        BeanValidator.check(userVo);
        checkValid(userVo);
        SysUser user= userMapper.selectByPrimaryKey(userVo.getId());
        user.setPassword(userVo.getPassword());
        user.setMail(userVo.getMail());
        user.setTelephone(userVo.getTelephone());
        user.setOperator(RequestHolder.getCurrentUser().getUsername());
        user.setOperateTime(new Date());
        userMapper.updateByPrimaryKey(user);
    }

    private void checkValid(ModifyUserVo userVo) {
        int i  = userMapper.checkEmailExist(userVo.getMail(),userVo.getId());
        if(i>0){
            throw  new ParamException("邮箱已被占用");
        }
        i = userMapper.checkPhoneExist(userVo.getTelephone(),userVo.getId());
        if(i>0){
            throw  new ParamException("手机已被占用");
        }
    }
}
